<template>
  <div id="menu-left-btn-xe601" v-if="props.moduleLists.length > 0" class="three-boxs">
    <t-tree
      ref="tree"
      :data="props.moduleLists"
      v-model:actived="actived"
      activable
      hover
      transition
      draggable
      :expandMutex="true"
      :activeMultiple="false"
      :keys="threeKeys"
      :expandAll="false"
      :expandOnClickNode="true"
      @Active="Active"
    >
      <template #label="{ node }">
        <div>
          <p class="three-title" v-if="node.data.name.length < 10">
            {{ node.data.name }}
          </p>
          <t-popup
            v-else
            attach="#menu-left-btn-xe601"
            overlayClassName="popup"
            class="placement top"
            :content="node.data.name"
            placement="top"
            showArrow
            destroyOnClose
          >
            <p class="three-title" style="width: 180px">
              {{ node.data.name }}
            </p>
          </t-popup>
        </div>
      </template>
      <template #icon="{ node }"
        ><i class="doorIcon" v-if="node.data.child && node.data.child.length > 0">&#xe664;</i></template
      >
      <template #operations="{ node }">
        <span class="total-text">{{ node.data.total }}</span>
      </template>
      <!-- v-if="node.data.children.length > 0" -->
    </t-tree>
  </div>
  <!-- @drag-start="handleDragStart"
   @drop="handleDrop"
      @drag-end="handleDragEnd"  
      @drag-over="handleDragOver" 
      @drag-leave="handleDragLeave" -->
</template>

<script setup lang="ts" name="itemView">
// @ts-nocheck
import auxiliaryModel from './auxiliaryModel.vue';
import { MessagePlugin } from 'tdesign-vue-next';
import messageModel from '@/components/messageModel/index.vue';
import { disableSort, moduleDelete, moduleSave, moduleList } from '@/api/desgin/desgin';
import { ref, reactive, nextTick, defineExpose, watch } from 'vue';

import { useProjectStore } from '@/store';
import { findIndex } from 'lodash';

const emit = defineEmits(['editItem', 'updateList']);
const tree = ref(null);
const actived = ref([-1]);
const delId = ref(0);
const visibleMessage = ref(false);
const parentId = ref(0);
const visible = ref(false); //添加辅助信息弹框
const loading = ref(false);
const threeKeys = {
  value: 'id',
  label: 'name',
  children: 'child',
};
const store = useProjectStore();
const value = ref(0);
const auxiliaryInfo = reactive({
  id: 0,
  name: '',
  description: '',
  coverUrl: '',
  parentId: 0,
  audio: {
    type: 3,
    url: '',
    description: '',
    name: '',
  },
  video: {
    type: 4,
    url: '',
    description: '',
    name: '',
  },
});
const clock = () => {};
const moveItem = reactive({
  info: null,
});
const props = defineProps({
  moduleLists: {
    type: Array,
  },
  ids: {
    type: Number,
  },
  parentId: {
    type: Number,
  },
  level: {
    type: Number,
  },
});

const Active = (value, content) => {
  // console.log(content.node.data);
  actived.value = [content.node.data.id];
  emit('editItem', content.node.data.id, content.node.data.name, 2);
  // value.value = value[0] ? value[0] : 0;
  // emit('editItem', actived.value[0], parentId);
  // if (actived.value[0]) {
  //   let parentId = tree.value.getParent(actived.value[0]); //获取指定节点父节点

  //   emit('editItem', actived.value[0], parentId);
  // }
  // console.log(actived.value[0], '1111111111111111111');
};
const topAdd = async (node: any) => {
  let parentId = tree.value.getParent(node.data.id); //获取指定节点父节点
  let arr = {
    id: 0,
    name: '示例单元',
    description: '',
    coverUrl: '',
    parentId: parentId ? parentId.data.id : 0,
    data: [],
  };
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    let res = await moduleSave(localStorage.getItem('projectId'), arr);
    if (res.statusCode == 200) {
      let arr = {
        children: [],
        id: res.data,
        level: node.data.level,
        parentId: parentId ? parentId.data.id : 0,
        remarks: null,
        sort: 9999,
        text: '示例单元',
        value: null,
      };
      if (parentId) {
        let soltInfo = tree.value.getItem(parentId.data.id);
        let arrNum = [];
        console.log(soltInfo.data);
        let find = soltInfo.data.children.findIndex((el) => {
          return el.id == node.data.id;
        });
        soltInfo.data.children.forEach((element, index) => {
          if (index === find) {
            if (find !== 0) {
              arrNum.push(res.data);
            } else {
              arrNum.unshift(res.data);
            }
          }
          arrNum.push(element.id);
        });
        // console.log(soltInfo);
        updataSort(parentId.data.id, arrNum);
      } else {
        // let soltInfo = tree.value.getItem();
        let soltInfo = node.getSiblings();
        let arrNum = [];
        console.log(soltInfo);
        let find = soltInfo.findIndex((el) => {
          return el.data.id == node.data.id;
        });
        soltInfo.forEach((element, index) => {
          if (index === find) {
            if (find !== 0) {
              arrNum.push(res.data);
            } else {
              arrNum.unshift(res.data);
            }
          }
          arrNum.push(element.data.id);
        });
        // console.log(soltInfo);
        updataSort(0, arrNum);
      }
      // tree.value?.insertBefore(node.data.id, arr);
      // tree.value.appendTo(node.data.id, arr);
      // MessagePlugin.success('保存成功');
    }
    loading.value = false;
  } catch (err) {
    loading.value = false;
    console.log(err);
  }
  // let soltInfo = tree.value.getItem(parentId);
  // console.log(soltInfo);
  //上方添加单元
  // let res = await disableSort(e.projectId, e.parentId, e.sort);
  //   if (res.statusCode == 200) {
  //     MessagePlugin.success(`排序成功`);
  //     tabListref.value.drops();
  //     initList();
  //   }
};
const bottomAdd = async (node: any) => {
  //下方添加单元
  let parentId = tree.value.getParent(node.data.id); //获取指定节点父节点
  let arr = {
    id: 0,
    name: '示例单元',
    description: '',
    coverUrl: '',
    parentId: parentId ? parentId.data.id : 0,
    data: [],
  };
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    let res = await moduleSave(localStorage.getItem('projectId'), arr);
    if (res.statusCode == 200) {
      let arr = {
        children: [],
        id: res.data,
        level: node.data.level,
        parentId: parentId ? parentId.data.id : 0,
        remarks: null,
        sort: 9999,
        text: '示例单元',
        value: null,
      };
      if (parentId) {
        let soltInfo = tree.value.getItem(parentId.data.id);
        let arrNum = [];
        console.log(soltInfo.data);
        let find = soltInfo.data.children.findIndex((el) => {
          return el.id == node.data.id;
        });
        soltInfo.data.children.forEach((element, index) => {
          // if (find === 0) {
          //   arrNum.push(res.data);
          // }

          // if (find !== 0 && index === find - 1) {
          //   arrNum.push(res.data);
          // }
          arrNum.push(element.id);
        });
        arrNum.splice(find + 1, 0, res.data);
        // console.log(soltInfo);
        updataSort(parentId.data.id, arrNum);
      } else {
        // let soltInfo = tree.value.getItem();
        let soltInfo = node.getSiblings();
        let arrNum = [];
        console.log(soltInfo);
        let find = soltInfo.findIndex((el) => {
          return el.data.id == node.data.id;
        });
        soltInfo.forEach((element, index) => {
          // if (find === 0) {
          //   arrNum.push(res.data);
          // }

          // if (find !== 0 && index === find - 1) {
          //   arrNum.push(res.data);
          // }
          arrNum.push(element.data.id);
        });
        arrNum.splice(find + 1, 0, res.data);
        // console.log(soltInfo);
        updataSort(0, arrNum);
      }
      tree.value.insertAfter(node.data.id, arr);
      // tree.value.appendTo(node.data.id, arr);
      // MessagePlugin.success('保存成功');
    }
    loading.value = false;
  } catch (err) {
    loading.value = false;
    console.log(err);
  }
};
const auxilaryclose = () => {
  visible.value = false;
};
const auxilarysubmit = () => {
  visible.value = false;
};
const childAdd = async (node: any) => {
  //添加子单元
  // let parentId = tree.value.getParent(node.data.id); //获取指定节点父节点
  // console.log(parentId);
  // return;
  let arr = {
    id: 0,
    name: '示例单元',
    description: '',
    coverUrl: '',
    parentId: node.data.id,
    data: [],
  };
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    let res = await moduleSave(localStorage.getItem('projectId'), arr);
    if (res.statusCode == 200) {
      let arr = {
        children: [],
        id: res.data,
        level: node.data.level + 1,
        parentId: 0,
        remarks: null,
        sort: 9999,
        text: '示例单元',
        value: null,
      };

      tree.value.appendTo(node.data.id, arr);
      MessagePlugin.success('保存成功');
    }
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
const auxiliaryAdd = (node: any) => {
  //添加辅助信息
  auxiliaryInfo.parentId = node.data.id;
  visible.value = true;
};
const delInfo = (node: any) => {
  delId.value = node.data.id;
  visibleMessage.value = true;
  // if (loading.value) {
  //   return;
  // }
  // loading.value = true;
  // moduleDelete(localStorage.getItem('projectId'), node.data.id).then((res: any) => {
  //   if (res.statusCode == 200) {
  //     MessagePlugin.success(`删除成功`);
  //   }
  // });
  //删除该目录
};
const closeClick = () => {
  //取消删除

  visibleMessage.value = false;
};
const submitClick = () => {
  // 删除单元;
  if (loading.value) {
    return;
  }
  loading.value = true;
  moduleDelete(localStorage.getItem('projectId'), delId.value).then((res: any) => {
    if (res.statusCode == 200) {
      MessagePlugin.success(`删除成功`);
      tree.value.remove(delId.value);
      delId.value = 0;
    }
    loading.value = false;
    visibleMessage.value = false;
  });
};
const moveTop = (node: any) => {
  let parentId = tree.value.getParent(node.data.id); //获取指定节点父节点
  let soltInfo = node.getSiblings();
  let arrNum = [];

  let find = soltInfo.findIndex((el) => {
    return el.data.id == node.data.id;
  });
  if (find == 0) {
    return;
  }
  let oldId = soltInfo[find].data.id; //排序前id
  let newId = soltInfo[find - 1].data.id; //即将替换的id
  soltInfo.forEach((element, index) => {
    arrNum.push(element.data.id);
  });
  arrNum[find] = newId;
  arrNum[find - 1] = oldId;

  updataSort(parentId ? parentId.data.id : 0, arrNum);
  //单元上移
};
const moveBottom = (node: any) => {
  let parentId = tree.value.getParent(node.data.id); //获取指定节点父节点
  let soltInfo = node.getSiblings();
  let arrNum = [];

  let find = soltInfo.findIndex((el) => {
    return el.data.id == node.data.id;
  });
  if (find == soltInfo.length - 1) {
    return;
  }
  let oldId = soltInfo[find].data.id; //排序前id
  let newId = soltInfo[find + 1].data.id; //即将替换的id
  soltInfo.forEach((element, index) => {
    arrNum.push(element.data.id);
  });
  arrNum[find] = newId;
  arrNum[find + 1] = oldId;

  updataSort(parentId ? parentId.data.id : 0, arrNum);
  //单元下移
};
const updataSort = async (parentId, sort) => {
  try {
    let res = await disableSort(localStorage.getItem('projectId'), parentId, sort);
    if (res.statusCode == 200) {
      emit('updateList');
    }
  } catch {}
};
// const handleDragStart = ({ node, e }) => {
//   // console.log('handleDragStart', node.value, e);
// };
// const handleDragEnd = ({ node, e }) => {
//   // console.log('handleDragEnd', node.value, e);
// };
// const handleDragOver = () => {};
// const handleDragLeave = ({ node, e }) => {
//   // console.log('handleDragLeave', node.value, e);
// };
// const handleDrop = ({ node, dropPosition, e }) => {
//   // console.log('handleDrop', node.value, dropPosition, e);
// };
// const emit = defineEmits(['navModel', 'delModule']);
</script>

<style lang="less" scoped>
.three-boxs {
  width: 284px;
}
:deep(.t-tree__item--open) {
  background: #f5f5f5;
}
:deep(.t-tree__item:hover) {
  background: #f0f0f0;
}
:deep(.t-is-active .t-tree__label) {
  background: transparent;
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.8);
  line-height: 24px;
}
:deep(.t-tree__item) {
  position: relative;
  z-index: 20;
  height: 44px;
}
:deep(.t-tree__operations) {
  position: relative;
}
:deep(.t-tree__icon) {
  margin-left: 20px;
  .doorIcon {
    transition: all 0.3s;
    font-size: 16px;
    color: RGBA(158, 158, 158, 1);
    transform: rotate(-90deg);
  }
}
:deep(.t-tree__item--open) {
  .t-tree__icon {
    .doorIcon {
      transform: rotate(0deg);
    }
  }
}
.editMenu {
  opacity: 0;
  position: relative;
  margin-right: 24px;
  z-index: 999;
  width: 24px;
  height: 24px;
  background: #d9d9d9;
  border-radius: 4px;

  .doorIcon {
    font-size: 24px;
    color: RGBA(134, 134, 134, 1);
  }
}

.editMenu-level {
  display: none;
  position: absolute;
  top: 0;
  right: -180px;
  padding: 4px 0;
  background: #ffffff;
  z-index: 999;
  box-shadow: 0px 5px 5px -3px rgba(0, 0, 0, 0.1), 0px 8px 10px 1px rgba(0, 0, 0, 0.06),
    0px 3px 14px 2px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
}
.editMenu-level-item {
  display: flex;
  align-items: center;
  width: 180px;
  height: 36px;

  padding: 0px 16px;
  .doorIcon {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.8);
  }
  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.8);
    line-height: 24px;
  }
  .editMenu-level-item-left-title {
    margin-left: 4px;
  }
}
.editMenu-level-item:hover {
  background: #f5f5f5;
}
.editMenu-level-item-1 {
  position: relative;
  .editMenu-level-item-left {
    .doorIcon {
      font-size: 16px;
      color: rgba(0, 0, 0, 0.8);
    }
    span {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.8);
      line-height: 24px;
    }
  }
}
:deep(.t-tree__item:hover) {
  height: 44px;
  .editMenu {
    opacity: 1 !important;
  }
}
.editMenu:hover {
  .editMenu-level {
    display: block;
    opacity: 1;
  }
}
.editMenu-child {
  display: none;
  position: absolute;
  top: 0;
  right: 0px;
  width: 184px;
  padding-left: 4px;
}
.editMenu-level-item-1:hover {
  .editMenu-child {
    display: block;
  }
}
.total-text {
  margin-right: 24px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.38);
  line-height: 22px;
}
:deep(.t-is-active) {
  background: #f5f5f5;
}
#menu-left-btn-xe601 {
  :deep(.t-popup__content) {
    background-color: #333;
    color: #fff;
    border-color: #333;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.15);

    font-size: 14px;
    font-weight: 400;
    color: #ffffff;
    line-height: 22px;
  }
  :deep(.placement) {
    // border-color: #333;
    background: transparent !important;
  }
  :deep(.t-popup[data-popper-placement^='left'] .t-popup__arrow::before) {
    background-color: #333;
    // border-color: #333;
  }
  :deep(.t-popup__arrow::before) {
    background-color: #333;
  }
}
.three-title {
  // display: flex;

  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.59);
  line-height: 24px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
:deep(.t-is-active) {
  background: #ffece6 !important;
  .three-title {
    color: #e62b17;
  }
}
:deep(.t-is-active .t-tree__label) {
  background: transparent !important;
}
</style>
